﻿
using XiangziProjectTemplete.Core.IRepository.Base;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Services.BASE;
using System.Threading.Tasks;
using System.Linq;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete;
using System;
using System.Collections.Generic;
using XiangziProjectTemplete.Core.IRepository.UnitOfWork;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Model.PostParamModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;

namespace XiangziProjectTemplete.Core.Services
{
    public class Base_StationServices : BaseServices<Base_Station>, IBase_StationServices
    {
        private readonly IBaseRepository<Base_Station> _dal;
        private readonly IBaseRepository<Base_BigMaterialStation> _dal_BigMaterialStation;
        private readonly IBaseRepository<Les_Mater_V_Station> _dal_Mater_V_Station;
        private readonly IBaseRepository<Base_CodeItems> _dal_Base_CodeItems;
        public Base_StationServices(
            IBaseRepository<Base_CodeItems> dal_Base_CodeItems,
            IBaseRepository<Les_Mater_V_Station> dal_Mater_V_Station,
            IBaseRepository<Base_Station> dal, IBaseRepository<Base_BigMaterialStation> dal_BigMaterialStation)
        {
            this._dal_Base_CodeItems = dal_Base_CodeItems;
            this._dal_Mater_V_Station = dal_Mater_V_Station;
            this._dal = dal;
            base.BaseDal = dal;
            this._dal_BigMaterialStation = dal_BigMaterialStation;
        }

        /// <summary>
        ///  验证站点编号和站点名称是否重复
        /// </summary>
        /// <param name="stationCode"></param>
        /// <param name="stationName"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> ValidateIsRepate(string stationCode, string stationName, int id = 0)
        {
            var isExistList = await _dal.Query(x => x.StationCode == stationCode);
            if (id != 0)
            {
                isExistList = isExistList.Where(x => x.Id != id).ToList();
            }
            if (!(isExistList == null || isExistList.Count == 0))
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点编号" + stationCode + "已经存在！"
                };
            }
            isExistList = await _dal.Query(x => x.StationName == stationName);
            if (id != 0)
            {
                isExistList = isExistList.Where(x => x.Id != id).ToList();
            }
            if (!(isExistList == null || isExistList.Count == 0))
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点名称" + stationCode + "已经存在！"
                };
            }
            return new MessageModel<bool>()
            {
                response = true,
                success = true
            };
        }

        /// <summary>
        /// 验证站点是否可以被使用
        /// </summary>
        /// <param name="stationId"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> ValidateStationIsAllowUse(int stationId)
        {
            var stationList = await _dal.Query(x => x.Id == stationId);
            if (stationList == null || stationList.Count == 0)
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点ID'" + stationId + "'不存在！"
                };
            }
            if (stationList.Count > 1)
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点ID'" + stationId + "'存在" + stationList.Count + "条数据！"
                };
            }
            var station = stationList[0];
            if (station.IsDeleted)
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点'" + station.StationName + "'已经被禁用！"
                };
            }
            else if (station.IsFull == 1)
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点'" + station.StationName + "'已经有货！"
                };
            }
            else if (station.IsLock == 1)
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点'" + station.StationName + "'已经被锁定！"
                };
            }

            //验证该站点是否在MVS表中
            var mvsList = await _dal_Mater_V_Station.Query(x => x.StationId == stationId);
            if (mvsList != null && mvsList.Count > 0)
            {
                return new MessageModel<bool>()
                {
                    response = false,
                    success = false,
                    msg = "站点'" + station.StationName + "'已经被物料绑定！"
                };
            }

            return new MessageModel<bool>()
            {
                response = true,
                success = true,
                msg = "验证站点可以被使用！"
            };
        }

        /// <summary>
        /// 获取库里的空库位
        /// </summary>
        /// <param name="storeArea">库存区域</param>
        /// <param name="stationPlaceTypeEnum">库位类型</param>
        /// <returns></returns>
        public async Task<MessageModel<Base_Station>> GetEmptyStation(string storeArea, StationPlaceTypeEnum stationPlaceTypeEnum)
        {
            var i_stationPlaceTypeEnum = Convert.ToInt32(stationPlaceTypeEnum).ToString();
            var emptyList = await _dal.Query(x => (x.IsDeleted == false) && x.StoreArea == storeArea && x.IsFull != 1 && x.IsLock != 1
            && x.PlaceType == i_stationPlaceTypeEnum);
            if (emptyList != null && emptyList.Count > 0)
            {
                return MessageModel<Base_Station>.Success("成功", emptyList[0]);
            }
            return MessageModel<Base_Station>.Success("成功", null);
        }

        /// <summary>
        /// 获取库里的空库位列表
        /// </summary>
        /// <param name="storeArea">库存区域</param>
        /// <param name="stationPlaceTypeEnum">库位类型</param>
        /// <returns></returns>
        public async Task<MessageModel<List<Base_Station>>> GetEmptyStationList(string storeArea_CodeItemId, int stationPlaceType_CodeItemId)
        {
            var emptyList = await _dal.Query(x =>
            (x.IsDeleted == false) &&
            x.StoreArea == storeArea_CodeItemId
            && (x.IsFull == null || x.IsFull == 0) && (x.IsLock == null || x.IsLock == 0) && x.PlaceType == stationPlaceType_CodeItemId.ToString());
            if (emptyList != null && emptyList.Count > 0)
            {
                return MessageModel<List<Base_Station>>.Success("成功", emptyList);
            }
            return MessageModel<List<Base_Station>>.Success("成功", null);
        }

        /// <summary>
        /// 获取库里的所有库位列表
        /// </summary>
        /// <param name="storeArea">库存区域</param>
        /// <param name="stationPlaceTypeEnum">库位类型</param>
        /// <returns></returns>
        public async Task<MessageModel<List<Base_Station>>> GetAllStationList(string storeArea_CodeItemId, int stationPlaceType_CodeItemId)
        {
            var stationList = await _dal.Query(x =>
            x.StoreArea == storeArea_CodeItemId
            && x.PlaceType == stationPlaceType_CodeItemId.ToString());
            if (stationList != null && stationList.Count > 0)
            {
                return MessageModel<List<Base_Station>>.Success("成功", stationList);
            }
            return MessageModel<List<Base_Station>>.Success("成功", null);
        }



        /// <summary>
        /// 获取库里可用空闲库位列表
        /// </summary>
        /// <param name="_base_CodeItemsServices"></param>
        /// <param name="storeArea"></param>
        /// <param name="StationPlaceType"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<Base_Station>>> GetEmptyStationList(IBase_CodeItemsServices _base_CodeItemsServices,
            StoreAreaEnum storeArea, StationPlaceTypeEnum StationPlaceType)
        {
            var area_codeItemsResult = await _base_CodeItemsServices.GetSingleCodeItemByCode(storeArea.ToString());
            var storeArea_CodeItemId = area_codeItemsResult.response.Id.ToString();

            var placetype_codeItemsResult = await _base_CodeItemsServices.GetSingleCodeItemByCode(Convert.ToInt32(StationPlaceType).ToString());
            var placetype_codeItemsId = placetype_codeItemsResult.response.Id;

            var stationList = await _dal.Query(x =>
            x.StoreArea == storeArea_CodeItemId
            && x.PlaceType == placetype_codeItemsId.ToString());
            if (stationList != null && stationList.Count > 0)
            {
                return MessageModel<List<Base_Station>>.Success("成功", stationList);
            }
            return MessageModel<List<Base_Station>>.Success("成功", null);
        }

        /// <summary>
        /// 新增或编辑站点
        /// </summary>
        /// <param name="param"></param>
        /// <param name="station"></param>
        /// <param name="addEditDeleteEnum"></param>
        /// <param name="_unitOfWork"></param>
        /// <param name="_user"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> AddEditStation(AddEditStationPostParam param,
            Base_Station station, AddEditDeleteEnum addEditDeleteEnum,
           IUnitOfWork _unitOfWork, IUser _user)
        {
            try
            {
                var operationRemark = "站点编号:" + param.StationCode + ",站点名称:" + param.StationName + ",";
                _unitOfWork.BeginTran();//开启事务

                switch (addEditDeleteEnum)
                {
                    case AddEditDeleteEnum.Add:
                        await _dal.Add(station);
                        break;
                    case AddEditDeleteEnum.Edit:
                        await _dal.Update(station);
                        break;
                }
                //保存绑定的大类物料信息
                var bsList = await _dal_BigMaterialStation.Query(x => x.StationId == station.Id);
                if (bsList != null && bsList.Count > 0)
                {
                    foreach (var item in bsList)
                    {
                        await _dal_BigMaterialStation.Delete(item);
                    }
                }
                if (param.BigMaterialStations != null && param.BigMaterialStations.Count > 0)
                {
                    foreach (var item in param.BigMaterialStations)
                    {
                        int[] arr = item;
                        Base_BigMaterialStation base_BigMaterialStation = new Base_BigMaterialStation()
                        {
                            Id = Guid.NewGuid().ToString(),

                            StationId = station.Id,
                            ProcedureCodeItemsId = arr[0],
                            BigMaterialCodeItemsId = arr[1],

                            CreateTime = DateTime.Now,
                            ModifyTime = DateTime.Now,
                            CreateBy = _user.Name,
                            ModifyBy = _user.Name,

                            OperationRemark = operationRemark + "绑定"
                        };
                        await _dal_BigMaterialStation.Add(base_BigMaterialStation);
                    }
                }

                _unitOfWork.CommitTran();
            }
            catch (System.Exception)
            {
                _unitOfWork.RollbackTran();
                throw;
            }

            return MessageModel<string>.Success("成功");
        }



        /// <summary>
        /// 根据工序获取工序下的站点列表（显示全部）
        /// </summary>
        /// <param name="procedureCodeItemId">工序的码表ID</param>
        /// <returns></returns>
        public async Task<MessageModel<List<Base_Station>>> GetStationsByProcedure(int procedureCodeItemId)
        {
            var stationList = await _dal.Query(x => x.AllowProcedure == procedureCodeItemId.ToString());
            if (stationList != null && stationList.Count > 0)
            {
                return MessageModel<List<Base_Station>>.Success("成功", stationList);
            }
            return MessageModel<List<Base_Station>>.Success("成功", null);
        }


        /// <summary>
        /// 根据用户的工序权限，获取他下面的工序获取工序下的站点列表（显示全部）
        /// </summary>
        /// <returns></returns>
        public async Task<MessageModel<List<Base_Station>>> GetAllStationsByUserProcedure(IUser user, ILes_ProcedureRoleServices les_ProcedureRoleServices)
        {
            List<Base_Station> stationList = new List<Base_Station>();
            //获取用户下的所有工序
            SeeProcedureRoleViewModel seeProcedureRoleViewModel = await les_ProcedureRoleServices.GetProcedureListByUser(user);
            if (seeProcedureRoleViewModel.IsHasAllProcedure)
            {//全部工序权限
                stationList = await _dal.Query();
            }
            else
            {//指定工序权限
                List<int> procedureList = seeProcedureRoleViewModel.ProcedureList;
                if (procedureList == null || procedureList.Count == 0)
                {
                    return MessageModel<List<Base_Station>>.Success("成功", null);
                }
                stationList = await _dal.Query(x => x.AllowProcedure != null && procedureList.Contains(Convert.ToInt32(x.AllowProcedure)));
            }
            return MessageModel<List<Base_Station>>.Success("成功", stationList);
        }
    }
}